package com.engineering.elink.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.engineering.elink.domain.Chapter;
import com.engineering.elink.domain.Course;
import com.engineering.elink.domain.Video;
import com.engineering.elink.domain.VideoBrowse;
import com.engineering.elink.domain.VideoSubtitle;
import com.engineering.elink.hessian.AliyunHessianService;
import com.engineering.elink.hessian.AuthHessianService;
import com.engineering.elink.service.VideoService;
import com.engineering.elink.videodao.ChapterMapper;
import com.engineering.elink.videodao.CourseMapper;
import com.engineering.elink.videodao.EnrollMapper;
import com.engineering.elink.videodao.VideoBrowseMapper;
import com.engineering.elink.videodao.VideoMapper;
import com.engineering.elink.videodao.VideoSubtitleMapper;
import com.engineering.elink.vo.ChapterVideoVo;
import com.engineering.elink.xaservice.EvaluateXaService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.zxy.core.Pagination;
import com.zxy.core.co.BaseCo;
import com.zxy.core.enums.ErrorType;
import com.zxy.core.util.CollectionUtil;
import com.zxy.core.util.JsonBinderUtil;
import com.zxy.core.util.ResJsonUtil;

/**
 * 
 * 视频业务实现类
 * 
 * ClassName: VideoServiceImpl <br/> 
 * Function: ADD FUNCTION. <br/> 
 * Reason: ADD REASON(可选). <br/> 
 * date: 2016年10月20日 下午11:29:45 <br/> 
 * 
 * @author zengxinyan 
 * @version  
 * @since JDK 1.8
 */
@Service
public class VideoServiceImpl implements VideoService{
	
	private Logger logger=Logger.getLogger(VideoServiceImpl.class);

	@Autowired
	private VideoMapper videoMapper;
	
	@Autowired
	private ChapterMapper chapterMapper;
	
	@Autowired
	private VideoBrowseMapper videoBrowseMapper;
	
	@Autowired
	private EvaluateXaService evaluateXaService;
	
	@Autowired
	private AuthHessianService authHessianService;
	
	@Autowired
	private AliyunHessianService aliyunHessianService;
	
	@Autowired
	private CourseMapper courseMapper;
	
	@Autowired
	private EnrollMapper enrollMapper;
	
	@Resource
	private VideoSubtitleMapper videoSubtitleMapper;
	
	/**
	 * 
	 * 简单描述该方法的实现功能（可选）. 
	 * @see com.engineering.elink.service.VideoService#getBrowseVideo(com.engineering.elink.co.BaseCo)
	 */
	@Override
	public Map<String, Object> getBrowseVideo(BaseCo co) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("list", videoMapper.getBrowseVideo(co));
		
		map.put("Pagination", new Pagination(co, videoMapper.selectCountBrowseVideo()));
		
		return map;
	}

	/**
	 * 
	 * 简单描述该方法的实现功能（可选）. 
	 * @see com.engineering.elink.service.VideoService#selectDefaultOneVideo(java.lang.Integer)
	 */
	@Override
	public Map<String,Object> selectDefaultOneVideo(Integer courseId,Integer freeStatus,String userId) {
		
		int count=enrollMapper.selectCountEnroll(courseId, userId);
		if(count<1){
			return ResJsonUtil.getMap(ErrorType.UN_ENROLL_COURSE_ERROR);
		}
		
		//取课程下所有节，按章排序，然后按章下面的每节进行排序
		List<Chapter> chList=chapterMapper.selectAllChapter(courseId);
	
		if(CollectionUtil.collectionIsNotEmpty(chList)){
			Video video=null;
			Map<String,Object> map=new HashMap<String,Object>();
			
			for(Chapter c:chList){
				//根据节ID，取免费和收费的第一个视频,如果当前节取不到视频则继续往下面取第二个节的视频
				video=videoMapper.selectDefaultOneVideo(c.getChapterId(),freeStatus);
				if(video!=null){
					
					//记录浏览记录
					videoBrowseMapper.insertSelective(new VideoBrowse(video.getVideoId(),userId));
					//更新视频浏览次数
					video.setVisitCount(video.getVisitCount()+1);
					videoMapper.updateByPrimaryKeySelective(video);
					
					map.put("videoInfo", video);
					//调视频播放hessian
					map.put("videoUrl", aliyunHessianService.getVideoSignatureUrl(video.getOssId()));
					
					//字幕
					map.put("videoSubTitleInfo", videoSubtitleMapper.getSubTitleByVideoId(video.getVideoId()));
					
					return ResJsonUtil.getMap(ErrorType.SUCCESS,map);
				}
					
			}
		}
		
		return ResJsonUtil.getMap(ErrorType.VIDEO_ERROR);
	}

	/**
	 * 
	 * 简单描述该方法的实现功能（可选）. 
	 * @see com.engineering.elink.service.VideoService#get(java.lang.Integer, java.lang.String)
	 */
	@Override
	public Map<String, Object> get(Integer videoId, Map<String,Object> userInfo) {
		
		//查type=0的
		Video v=videoMapper.selectVideoByType(videoId, 0);
		if(v!=null){
			
			String userId=null;
			int userType=0;
			if(userInfo!=null && userInfo.get("userId")!=null){
				userId =  userInfo.get("userId").toString();
			}
			if(userInfo!=null && userInfo.get("userType")!=null){
				//只有个人用户才能够投递//1个人2企业
				userType=(int)userInfo.get("userType");
			}
			
			//未登陆
			if(StringUtils.isEmpty(userId)){
				return ResJsonUtil.getMap(ErrorType.NEED_LOGIN);
			}
			//只有审核通过可播放
			if(v.getStatus()!=1){
				return ResJsonUtil.getMap(ErrorType.UN_PLAY_VIDEO_ERROR);
			}
			
			if(userType==1){
				List<Course> courseList=courseMapper.selectCourseByVideoId(videoId);
				Course course=null;
				if(CollectionUtil.collectionIsNotEmpty(courseList)){
					course=courseList.get(0);
				}
				if(course==null){
					return ResJsonUtil.getMap(ErrorType.COURSE_ERROR);
				}
				int count=enrollMapper.selectCountEnroll(course.getCourseId(), userId);
				if(count<1){
					return ResJsonUtil.getMap(ErrorType.UN_ENROLL_COURSE_ERROR);
				}
			}
		
			//记录浏览记录
			videoBrowseMapper.insertSelective(new VideoBrowse(videoId,userId));
			//更新视频浏览次数
			v.setVisitCount(v.getVisitCount()+1);
			videoMapper.updateByPrimaryKeySelective(v);
		
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("videoInfo", v);
			//调视频播放hessian
			map.put("videoUrl", aliyunHessianService.getVideoSignatureUrl(v.getOssId()));
			
			//字幕
			map.put("videoSubTitleInfo", videoSubtitleMapper.getSubTitleByVideoId(videoId));
			
			return ResJsonUtil.getMap(ErrorType.SUCCESS,map);
		}
		
		return ResJsonUtil.getMap(ErrorType.VIDEO_ERROR);
		
		
	}

	/**
	 * 
	 * 简单描述该方法的实现功能（可选）. 
	 * @see com.engineering.elink.service.VideoService#selectNextVideo(java.lang.Integer, java.lang.Integer, java.lang.Integer)
	 */
	@Override
	public Video selectNextVideo(Integer courseId, Integer freeStatus,Integer videoId,String userId) {
		//取课程下所有节，按章排序，然后按章下面的每节进行排序
		List<Chapter> chList=chapterMapper.selectAllChapter(courseId);
		if(CollectionUtil.collectionIsNotEmpty(chList)){
			for(Chapter c:chList){
				//根据节ID，取免费和收费的第一个视频,如果当前节取不到视频则继续往下面取第二个节的视频
				Video v=videoMapper.selectDefaultOneVideo(c.getChapterId(),freeStatus);
				if(v!=null && !videoId.equals(v.getVideoId())){
					//记录浏览记录
					videoBrowseMapper.insertSelective(new VideoBrowse(v.getVideoId(),userId));
					//更新视频浏览次数
					v.setVisitCount(v.getVisitCount()+1);
					videoMapper.updateByPrimaryKeySelective(v);
					
					return v;
				}
			}
		}
		
		return null;
	}
	
	/**
	 * 
	 * 简单描述该方法的实现功能（可选）. 
	 * @see com.engineering.elink.service.VideoService#getSameVideo(com.engineering.elink.co.BaseCo)
	 */
	@Override
	public Map<String, Object> getSameVideo(BaseCo co,Integer videoId) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		BaseCo bco=new BaseCo();
	
		bco.setPageSize(4);
		
		map.put("list", videoMapper.getSameVideo(bco,videoId));
		
		return map;
	}

	@Override
	public Map<String, Object> syncVideo(String cloudAddress, String seed, String authToken, String videoJsonStr,String jsonStr) {
		
		logger.info("同步视频开始！！！");
		try {
			
			String userId = authHessianService.checkAuthToken(seed, authToken);
			if(StringUtils.isEmpty(userId)){
				return ResJsonUtil.getMap(ErrorType.USER_SYNC_ERROR);
			}
			
			Video video=JsonBinderUtil.fromJson(videoJsonStr, Video.class);
			if(video==null){
				return ResJsonUtil.getMap(ErrorType.REQUEST_PARAMS_ERROR);
			}
			if(StringUtils.isBlank(video.getVideoName())){
				return ResJsonUtil.getMap(ErrorType.VIDEO_NAME_ERROR);
			}
			
			List<VideoSubtitle> vsList=JsonBinderUtil.fromJsontolist(jsonStr,new TypeReference<List<VideoSubtitle>>(){});
//			if(CollectionUtil.collectionIsEmpty(vsList)){
//				return ResJsonUtil.getMap(ErrorType.REQUEST_PARAMS_ERROR);
//			}
			
			synchronized (this) {
				evaluateXaService.syncVideo(cloudAddress,userId,video,vsList);
			}
			
			return ResJsonUtil.getMap(ErrorType.SUCCESS);
			
		} catch (Exception e) {
			e.printStackTrace();
			return ResJsonUtil.getMap(ErrorType.VIDEO_SYNC_ERROR,e.getMessage());
		} 
		
	}
	
	@Override
	public Map<String, Object> deleteVideo(String videoIds) {
		
		if(StringUtils.isNotEmpty(videoIds)){
			videoMapper.updateBatchByStatus(StringUtils.split(videoIds, ','));
		}
		
		return ResJsonUtil.getMap(ErrorType.SUCCESS);
	}

	@Override
	public Map<String, Object> updateVideo(String videoJsonStr) {
		
		try{
			
			Video updateVideo=JsonBinderUtil.fromJson(videoJsonStr, Video.class);
			if(updateVideo==null){
				return ResJsonUtil.getMap(ErrorType.UPDATE_VIDEO_JSON_ERROR);
			}
			Video video=videoMapper.selectByPrimaryKey(updateVideo.getVideoId());
			if(video==null){
				return ResJsonUtil.getMap(ErrorType.VIDEO_ERROR);
			}
			video.setVideoName(updateVideo.getVideoName());
			video.setIntroduction(updateVideo.getIntroduction());
			video.setCopyright(updateVideo.getCopyright());
			
			videoMapper.updateByPrimaryKeySelective(video);
			
			return ResJsonUtil.getMap(ErrorType.SUCCESS);
		
		} catch (Exception e) {
			e.printStackTrace();
			return ResJsonUtil.getMap(ErrorType.UPDATE_VIDEO_ERROR,e.getMessage());
		} 
	
	}

	@Override
	public Map<String, Object> getList(String videoName, Integer status, BaseCo co,String userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("videoName", videoName);
		map.put("status", status);
		map.put("co", co);
		map.put("userId", userId);
		
		List<ChapterVideoVo> videoList=videoMapper.getList(map);
		int count=videoMapper.selectCountList(map);
		map.clear();
		
		map.put("list",videoList);
		map.put("Pagination", new Pagination(co, count));
		
		return map;
	}
	
}
